package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.iot.common.utils.Event;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.Robot;
import com.iot.product.sweeper.bean.RobotStatus;
import com.iot.product.sweeper.config.SweeperProductConfig;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanParam;
import com.iot.sweeper.param.RemoteControlParam;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.RemotecontrolActivityBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.CommonConfirmDialog2;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.StatusBarColorUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.CustomEditBottonDialog;
import com.yx.cloud.view.RockerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

/**
 * 遥控器界面
 */
public class RemoteControlActivity extends BaseActivity implements CustomEditBottonDialog.CallBackValue, View.OnClickListener {

    private static final String TAG = "RemoteControlActivity";
    private CleanSettings settings;
    private Robot robot;
    private RemotecontrolActivityBinding binding;
    CountDownTimer dust_timer = new CountDownTimer(16000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dustCollectHintDialog("", getResources().getString(R.string.Finished_collecting_dust));
                }
            });
        }
    };
    //360度旋转遥控器
    private RockerView mController;
    private Dialog dialog;
    private boolean touchTag = true;
    private String instruct = "";
    private final Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            Log.d(TAG, " : runnable :     1111              " + ClickUtils.setTiming());
            while (touchTag) {
                Log.d(TAG, "runnable :                   " + instruct);
                RemoteControlParam param = new RemoteControlParam();
                if (instruct.equals("left")) {
                    param.setMotion(RemoteControlParam.Movement.LEFT);
                } else if (instruct.equals("right")) {
                    param.setMotion(RemoteControlParam.Movement.RIGHT);
                } else if (instruct.equals("forward")) {
                    param.setMotion(RemoteControlParam.Movement.FORWORD);
                } else if (instruct.equals("stop")) {
                    param.setMotion(RemoteControlParam.Movement.STOP);
                }
                AppContext.getProductService().remoteControl(param);
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (!touchTag) {
                // Log.d(TAG, touchTag + " : runnable :     22222222              " + instruct);
                RemoteControlParam param = new RemoteControlParam();
                param.setMotion(RemoteControlParam.Movement.STOP);
                AppContext.getProductService().remoteControl(param);
            }
        }
    };
    private JSONObject productConfig;
    private Thread thread;
    CountDownTimer setTimer = new CountDownTimer(50, 100) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d(TAG, " : setTimer :                  onTick ");
        }

        @Override
        public void onFinish() {
            Log.d(TAG, " : setTimer :                  onFinish ");
            thread = new Thread(runnable);
            thread.start();
        }
    };


    @Override
    public void onCreate() {
        binding = RemotecontrolActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
        //360度旋转遥控器
        mController = findViewById(R.id.Nav_Controller);
        productConfig = AppContext.getConfig();
        initData();
    }

    private void initData() {

        robot = AppContext.get().getCurrentDevice();
        settings = robot.getCleanSettings();

        int workMode = robot.getRobotStatus().getWorkMode();
        int workState = robot.getRobotStatus().getWorkState();
        if (workMode == RobotStatus.MODE_SPOT_CLEAN && workState == RobotStatus.STATE_WORKING) {
            binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_Pause));
            binding.ivPartClean.setImageResource(R.mipmap.partial_cleaning_pause);
        } else {
            if (productConfig.optBoolean(ProductConfigConstants.isInxni)) {
                binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_SpotClean));
            } else {
                binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_Part_Cleaning));
            }
            binding.ivPartClean.setImageResource(R.mipmap.partial_cleaning);

        }

        //360度 遥控器数据回调
        if (mController != null) {
            mController.setCallBackMode(RockerView.CallBackMode.CALL_BACK_MODE_STATE_CHANGE);
            mController.setOnShakeListener(RockerView.DirectionMode.DIRECTION_8, new RockerView.OnShakeListener() {
                @Override
                public void onStart() {
                    Log.d(TAG, "摇动方向 : 开始 开始 : ");
                    touchTag = true;
                    setTimer.start();
                }

                @Override
                public void direction(RockerView.Direction direction) {
                    // Log.d(TAG, "摇动方向 : " + direction);
                    switch (direction) {
                        case DIRECTION_LEFT:
                        case DIRECTION_UP_LEFT:
                        case DIRECTION_DOWN_LEFT:
                            // "左 左下 左下";
                            instruct = "left";
                            binding.ivLeft.setVisibility(View.VISIBLE);
                            binding.ivRight.setVisibility(View.INVISIBLE);
                            binding.ivUp.setVisibility(View.INVISIBLE);
                            break;
                        case DIRECTION_RIGHT:
                        case DIRECTION_UP_RIGHT:
                        case DIRECTION_DOWN_RIGHT:
                            //"右 右上 右下";
                            instruct = "right";
                            binding.ivLeft.setVisibility(View.INVISIBLE);
                            binding.ivRight.setVisibility(View.VISIBLE);
                            binding.ivUp.setVisibility(View.INVISIBLE);
                            break;
                        case DIRECTION_UP:
                            //"上";
//                            Log.d(TAG, "摇动方向 : 上");
                            instruct = "forward";
                            binding.ivLeft.setVisibility(View.INVISIBLE);
                            binding.ivRight.setVisibility(View.INVISIBLE);
                            binding.ivUp.setVisibility(View.VISIBLE);
                            break;
                        case DIRECTION_DOWN:
                            //"下";
                            //Log.d(TAG, "摇动方向 : 下");
                            //touchTag = false;
                            instruct = "stop";  // 往下拖的时候 发停止
                            binding.ivLeft.setVisibility(View.INVISIBLE);
                            binding.ivRight.setVisibility(View.INVISIBLE);
                            binding.ivUp.setVisibility(View.INVISIBLE);
                            break;
                    }
                }

                @Override
                public void onFinish() {
//                    Log.d(TAG, "摇动方向 : 抬起 抬起");
                    //抬起
                    touchTag = false;
                    instruct = "stop";
                    binding.ivLeft.setVisibility(View.INVISIBLE);
                    binding.ivRight.setVisibility(View.INVISIBLE);
                    binding.ivUp.setVisibility(View.INVISIBLE);
                    binding.ivDown.setVisibility(View.INVISIBLE);
                    setTimer.cancel();
                }
            });
        }

        binding.ivControlReturn.setOnClickListener(this);
        binding.llRemoteControlRecharge.setOnClickListener(this);
        binding.llRemoteControlPattern.setOnClickListener(this);
        binding.llRemoteControlPartialCleaning.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_controlReturn) {
            onBackPressed();
        } else if (id == R.id.ll_remoteControlPattern) {
            //模式
//                showBottomDialog();
            Robot device = AppContext.get().getCurrentDevice();
            CleanSettings settings = device.getCleanSettings();
            int suction = settings.getSuction();//获取吸力
            int water = settings.getMopHumidity();//获取水量
            CustomEditBottonDialog customEditBottonDialog = new CustomEditBottonDialog(this, suction, water, 1);
            customEditBottonDialog.show();
            customEditBottonDialog.setCallBackValue(this);
        } else if (id == R.id.ll_remoteControl_PartialCleaning) {
            //局部清扫
            int workState = robot.getRobotStatus().getWorkState();
            int workMode = robot.getRobotStatus().getWorkMode();
            if (workState == RobotStatus.STATE_CHARGING) {
                String toastStr = "";
                toastStr = getString(R.string.U_T_RemoteMode_SpotClean);
                if (productConfig.optBoolean(ProductConfigConstants.isInxni)) { //以内产品的文案是定点清扫 其他是局部清扫
                    toastStr = getString(R.string.U_T_RemoteMode_SpotClean);
                } else {
                    toastStr = getString(R.string.U_Part_Cleaning_Tip);
                }
                ToastUtil.show(RemoteControlActivity.this, toastStr, Toast.LENGTH_SHORT);
                return;
            }

            //部分产品 开始局部清扫需要先发退出遥控模式
            if (productConfig.optBoolean(ProductConfigConstants.spotCleanStopControl)) {
                AppContext.getProductService().stopRemoteControl();//退出遥控模式
            }
            if (workState == RobotStatus.STATE_WORKING) { //TODO 这里什么建图中 定位中的状态也要判断 应该
                if (workMode == RobotStatus.MODE_SPOT_CLEAN) {
                    AppContext.getProductService().pauseSweep();//发送暂停清扫
                } else if (workMode == RobotStatus.MODE_RECHARGE) {
                    //回冲中 发暂停 再发开始定点
                    AppContext.getProductService().pauseRecharge();

                    CleanParam param = new CleanParam();
                    param.setType(RobotStatus.MODE_SPOT_CLEAN);
                    AppContext.getProductService().startSweep(param);//发送开始
                } else {
                    //其他模式清扫中 弹窗停止
                    currentTaskDialog(getString(R.string.H_EndTask));
                }
            } else if (workState == RobotStatus.STATE_PAUSE) {
                if (workMode == RobotStatus.MODE_SPOT_CLEAN) {
                    //定点清扫的暂停  发继续
                    if (productConfig.optInt(ProductConfigConstants.product_type) != ProductConfigConstants.PRODUCT_TYPE_GYRO) {
                        AppContext.getProductService().continueSweep(null);//发送继续
                    } else {
                        CleanParam param = new CleanParam();
                        param.setType(RobotStatus.MODE_SPOT_CLEAN);
                        AppContext.getProductService().startSweep(param);//发送开始
                    }
                } else {
                    //其他清扫的暂停 发开始
                    CleanParam param = new CleanParam();
                    param.setType(RobotStatus.MODE_SPOT_CLEAN);
                    AppContext.getProductService().startSweep(param);//发送开始
                }
            } else {
                CleanParam param = new CleanParam();
                param.setType(RobotStatus.MODE_SPOT_CLEAN);
                AppContext.getProductService().startSweep(param);//发送开始
            }
        } else if (id == R.id.ll_remoteControlRecharge) {
            //回充
            outRemoteControlDialog(getString(R.string.MO_Recharge_Tip));
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        //退出遥控
        if (productConfig.optBoolean(ProductConfigConstants.backStopControl)) {
            AppContext.getProductService().stopRemoteControl();//退出遥控模式
        }
        Intent_utils.backIntent(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_DUST_COLLECTION:
                //集尘
                break;
            case Event.MSG_ROBOT_STATE:
                //状态上报
//                binding.lottieAnimationView.setVisibility(View.GONE);
                int workMode = robot.getRobotStatus().getWorkMode();
                int workState = robot.getRobotStatus().getWorkState();
                if (workMode == RobotStatus.MODE_SPOT_CLEAN && workState == RobotStatus.STATE_WORKING) {
                    binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_Pause));
                    binding.ivPartClean.setImageResource(R.mipmap.partial_cleaning_pause);
                } else {
                    if (productConfig.optBoolean(ProductConfigConstants.isInxni)) {
                        binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_SpotClean));
                    } else {
                        binding.tvRemoteControlSpotCleaning.setText(getString(R.string.U_Part_Cleaning));
                    }
                    binding.ivPartClean.setImageResource(R.mipmap.partial_cleaning);
                }
                break;
        }
    }

    /**
     * 退出遥控Dialog
     */
    private void outRemoteControlDialog(String dialogTitle) {
        dialog = new Dialog(RemoteControlActivity.this);
        dialog.setContentView(R.layout.content_centered_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnOutLoginConfirm = dialog.findViewById(R.id.btn_centered_Confirm);
        TextView mBtnOutLoginCancel = dialog.findViewById(R.id.btn_centered_Cancel);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_centered_dialogTitle);

        mTvDialogTitle.setText(dialogTitle);
        mBtnOutLoginConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if (productConfig.optBoolean(ProductConfigConstants.rechargeStopControl)) {
                    AppContext.getProductService().stopRemoteControl();
                }

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.i(TAG, "AAAAAA---开始回充-- ");
                AppContext.getProductService().startRecharge();

                Intent_utils.enterIntent(RemoteControlActivity.this, MainActivity2.class);
                dialog.dismiss();
                finish();
            }
        });
        mBtnOutLoginCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void dustCollectHintDialog(String dialogTitle, String content) {
        Dialog dialog = new Dialog(RemoteControlActivity.this);
        dialog.setContentView(R.layout.hint_dialog);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCanceledOnTouchOutside(false);
        TextView mBtnCenteredConfirm = dialog.findViewById(R.id.btn_hintConfirm);
        TextView mTvDialogTitle = dialog.findViewById(R.id.tv_dialogHintTitle);
        TextView mTvDialogContent = dialog.findViewById(R.id.tv_hint_content);
        mTvDialogTitle.setText(dialogTitle);
        mTvDialogContent.setText(content);
        mBtnCenteredConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            }
        });
        mBtnCenteredConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                return true;
            }
        });
        dialog.show();
    }

    private void currentTaskDialog(String content) {
        CommonConfirmDialog2.newBuilder()
                .context(RemoteControlActivity.this)
                //TODO 开启定位服务 没给文本
                .message(content)
                .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                    @Override
                    public boolean onConfirm() {
                        //停止清扫任务
                        AppContext.getProductService().stopSweep();
                        //开始局部清扫
                        CleanParam param = new CleanParam();
                        param.setType(RobotStatus.MODE_SPOT_CLEAN);
                        AppContext.getProductService().startSweep(param);//发送开始
                        return true;
                    }

                    @Override
                    public boolean onCancel() {
                        return true;
                    }
                }).build().show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "退出遥控模式 ");
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void SendCleanSetMessage(int suction, int water, int times) {
//        String fanString = LFDateUtils.getFanString(suction);
//        String waterString = LFDateUtils.getWaterString(water);
//        AppContext.getService().setCleanSettings(CleanSettingParam.newBuilder().suction(suction).mopHumidity(water).build());
    }

}

